from lxml import etree
from selenium.webdriver.common.by import By
from support.network.browser import Browser

class Movie:
    POSTER_ASPECT_RATIO = 1.3
    LIMIT_IMG_SEARCH_COUNT = 5
    LIMIT_MOVIE_SEARCH_COUNT = 1
    DOMAIN_DOUBAN = "https://search.douban.com/movie/subject_search?search_text="
    DOMAIN_BAIDU = "https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111110&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&oq=%E6%B5%81%E6%B5%AA%E5%9C%B0%E7%90%832%E2%80%8E+%282023%29&rsp=-1&word="

    def __init__(self, host):
        self.browser = Browser(host, Browser.TYPE_FIREFOX)

    def exit(self):
        self.browser.exit()

    def query(self, keyword):
        movieInfo = self.__queryBaseInfo__(keyword)
        for info in movieInfo:
            info['cover'] = self.__queryCover__(info['title'])
        return movieInfo

    def __queryBaseInfo__(self, keyword):
        info = None
        tabid = None
        try:
            tabid, html = self.browser.open("{}{}".format(Movie.DOMAIN_DOUBAN, keyword), timeout=10,
                    waitConditions=[
                        {"type":Browser.ELEMENT_VISIBLE, "element":(By.ID, 'root')}
                    ])
            orgData = etree.HTML(html)
            emt = orgData.xpath('//h1[contains(text(), \"{}\")]/parent::*/parent::*/div'.format(keyword))
            if(len(emt) < 3): raise Exception("Douban format was Changed")
            if(emt[1].xpath('.//div[contains(text(),"没有找到")]')): raise Exception("Cannot found {}".format(keyword))
            info = self.__parseMovieData__(emt[1].xpath('.//div[@class="item-root"]'))
        finally:
            self.browser.close(tabid)
        return info

    def __parseMovieData__(self, movies):
        lst = []
        for index in range(0, min(len(movies), Movie.LIMIT_MOVIE_SEARCH_COUNT)):
            movie = movies[index]
            rating = "暂无评分"
            title = movie.xpath('.//a[@class="title-text"]')[0].text
            ratingData = movie.xpath('.//span[@class="rating_nums"]')
            if(ratingData):rating = ratingData[0].text
            meta = movie.xpath('.//div[@class="meta abstract"]')[0].text
            meta2 = movie.xpath('.//div[@class="meta abstract_2"]')[0].text
            lst.append({"title":title, "rating":rating, "meta":meta, "meta2":meta2})
        return lst

    def __queryCover__(self, title):
        tabid = None
        cover = None
        aspect = 10
        try:
            tabid, html = self.browser.open("{}《{}》海报".format(Movie.DOMAIN_BAIDU, title), timeout=10,
                    waitConditions=[
                        {"type":Browser.ELEMENT_VISIBLE, "element":(By.CLASS_NAME, 'imgpage')}
                    ])
            orgData = etree.HTML(html)
            emt = orgData.xpath('//div[@class="imgpage"]//li[@class="imgitem"]//img')
            for index in range(0, min(len(emt), Movie.LIMIT_IMG_SEARCH_COUNT)):
                img = emt[index]
                style = img.get("style").strip(';').split(';')
                size = {}
                radio = aspect
                for s in style:
                    kv = s.split(':')
                    try:
                        size[kv[0].strip()] = int(kv[1].strip().replace('px', ''))
                    except:
                        size[kv[0].strip()] = 0
                if('height' in size.keys() and 'width' in size.keys() and size['height'] > size['width']): radio = abs(size['width']/size['height'] - Movie.POSTER_ASPECT_RATIO)
                if(radio < aspect):
                    aspect = radio
                    cover = img.get("src")
        except Exception as e:
           print(e) 
        finally:
            self.browser.close(tabid)
            return cover
